<?php

require_once('config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/SmartyMaptrick.class.php');
require_once(SITE_ROOT . 'class/logic/Registration.class.php');
require_once(SITE_ROOT . 'class/logic/LogicHoC.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'config/session.php');

$logic = LogicHoC::getInstance();
$smarty = new SmartyMaptrick();

if (count($_POST) > 0 && ($_POST["rnd"] != $_SESSION["rnd_maptrick"] || $_POST["rnd"] == "" || !isset($_POST["rnd"]))) {
	$_SESSION = array();
	$_POST = array();
}

if (preg_match("/^[0-9]{1,3}$/", $_POST['select_countries'])) $countryID = $_POST['select_countries'];
if (preg_match("/^[0-9]{1,2}$/", $_POST['select_divisions'])) $divisionID = $_POST['select_divisions'];
if (preg_match("/^[0-9]{1,6}$/", $_POST['select_leagues'])) $leagueID = $_POST['select_leagues'];

if (preg_match("/^[A-Za-z_-]{1,32}$/", $_POST['hidden'])) $hidden = $_POST['hidden'];

if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier']) && count($_POST) == 0) {
	try {
		$register = new Registration();
		$register->connect($_GET['oauth_token'], $_GET['oauth_verifier']);
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}

if ($hidden == 'login') {
	try {
		$register = new Registration();
		$callback = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
		$url = $register->login($callback);
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}
else if ($hidden == 'logout') {
	try {
		$register = new Registration();
		$register->logout();
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}
else if ($hidden == 'fetch') {
	if ($leagueID != 0) {
		try {
			$league = $logic->fetchLeague($leagueID);
		}
		catch (Exception $e) {
			$errorCode = substr($e->getMessage(), strpos($e->getMessage(), "(") + 1, strpos($e->getMessage(), ")") - strpos($e->getMessage(), "(") - 1);
			switch ($errorCode) {
				case 0: {
					unset($_SESSION['login']);
					unset($_SESSION['login_team']);
					unset($_SESSION['HT']);
					$smarty->assign('message', 'Timeout!');
					break;
				}
				default: $smarty->assign('error', "An error has occured! Please try again later.");
			}
		}
	}
	else $smarty->assign('error', "You have to choose a league!");
}

if ($hidden == 'login') {
	header('Location: '. $url);
}
else {
	$smarty->assign('action', $_SERVER['PHP_SELF']);
	$smarty->assign('loggedIn', $_SESSION['login']);

	// assign the important attributes for the header
	$smarty->assign('title', 'Maptrick');
	$smarty->assign('hoc_active', 'active');

	$_SESSION["rnd_maptrick"] = hash_hmac("sha256", rand(1000000000, 9999999999), SCRIPT_PWD);
	$smarty->assign("rnd_maptrick", $_SESSION["rnd_maptrick"]);
	
	if ($_SESSION['login'] && isset($_SESSION['login_team'])) {
		$login_team = $_SESSION['login_team'];
		$smarty->assign('login_user', $login_team->getUserName());
		$smarty->assign('login_team', $login_team->getName());
		$smarty->assign('login_teamID', $login_team->getTeamID());
		if ($login_team->getLeague() != null) {
			$smarty->assign('login_leagueID', $login_team->getLeague()->getLeagueID());
			$smarty->assign('login_league', $login_team->getLeague()->getName());
		}
	}

	$smarty->assign('introduction', "<p>You can import a Hattrick league here. You have to be logged in to do anything. To import a league choose the league with the drop down boxes and press \"Fetch\" afterward. You have to select a country first, then the division and at last the league. If everything was successfull a link to the Hall of Cool is presented to you where you can update all the members of the league then.</p>");

	$countries = $logic->getCountries();
	$smarty->assign('countries', $countries);

	if ($leagueID != 0) {
		$league = $logic->getLeague($leagueID);
		if (isset($league)) {
			$smarty->assign('selected_country', $league->getDivision()->getCountry()->getCountryID());
			$smarty->assign('divisions', $logic->getDivisions($league->getDivision()->getCountry()->getCountryID()));
			$smarty->assign('selected_division', $league->getDivision()->getDivisionID());
			$smarty->assign('leagues', $logic->getLeagues($league->getDivision()->getCountry()->getCountryID(), $league->getDivision()->getDivisionID()));
			$smarty->assign('selected_league', $league->getLeagueID());
		}
	}
	else if ($countryID != 0 && $divisionID != 0) {
		$smarty->assign('selected_country', $countryID);
		$smarty->assign('divisions', $logic->getDivisions($countryID));
		$smarty->assign('selected_division', $divisionID);
		$smarty->assign('leagues', $logic->getLeagues($countryID, $divisionID));
	}
	else if ($countryID  != 0) {
		$smarty->assign('selected_country', $countryID);
		$smarty->assign('divisions', $logic->getDivisions($countryID));
	}

	if ($league != null) {

		foreach ($countries as $country) {
			if ($country->getCountryID() == $league->getDivision()->getCountry()->getCountryID()) {
				$selectedCountry = $country;
				break;
			}
		}

		$smarty->assign('info', "All teams, except for bot and ownerless teams, which play in the league \"" . $league->getName() . "\" in " . $selectedCountry->getName() . " were imported successfully. You can take a look at the league in the Hall of Cool by clicking <a href=\"hallofcool.php?league=" . $league->getLeagueID() . "\">here</a>.");
	}

	$smarty->display('header.tpl');
	$smarty->display('leagueimport.tpl');
	$smarty->display('footer.tpl');
}

?>